package com.newshub.business.service.impl;

import com.newshub.business.entity.Category;
import com.newshub.business.dto.CategoryQueryDTO;
import com.newshub.business.dto.PageResult;
import com.newshub.business.mapper.CategoryMapper;
import com.newshub.business.service.CategoryService;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * 分类服务实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    
    @Autowired
    private CategoryMapper categoryMapper;
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "获取所有分类")
    public List<Category> getAllCategories() {
        return categoryMapper.selectAllCategories();
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "根据ID获取分类")
    public Category getCategoryById(Integer id) {
        return categoryMapper.selectById(id);
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "根据名称获取分类")
    public Category getCategoryByName(String name) {
        return categoryMapper.selectByName(name);
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "添加分类")
    public boolean addCategory(Category category) {
        // 设置默认值
        if (category.getStatus() == null) {
            category.setStatus(1); // 默认启用
        }
        if (category.getLevel() == null) {
            category.setLevel(1); // 默认顶级
        }
        if (category.getSortOrder() == null) {
            category.setSortOrder(0); // 默认排序
        }
        if (category.getCreatedAt() == null) {
            category.setCreatedAt(LocalDateTime.now());
        }
        if (category.getUpdatedAt() == null) {
            category.setUpdatedAt(LocalDateTime.now());
        }
        
        return categoryMapper.insert(category) > 0;
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "更新分类")
    public boolean updateCategory(Category category) {
        category.setUpdatedAt(LocalDateTime.now());
        return categoryMapper.updateById(category) > 0;
    }
    
    @Override
    @BusinessLog(level = LogLevel.WARN, description = "删除分类")
    public boolean deleteCategory(Integer id) {
        return categoryMapper.deleteById(id) > 0;
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "分页查询分类")
    public PageResult<Category> getCategoryPage(CategoryQueryDTO queryDTO) {
        // 计算偏移量
        int offset = (queryDTO.getPageNum() - 1) * queryDTO.getPageSize();
        
        // 查询数据
        List<Category> list = categoryMapper.selectByPage(
            queryDTO.getName(), 
            queryDTO.getCode(), 
            queryDTO.getStatus(), 
            offset, 
            queryDTO.getPageSize()
        );
        
        // 查询总数
        long total = categoryMapper.countByPage(
            queryDTO.getName(), 
            queryDTO.getCode(), 
            queryDTO.getStatus()
        );
        
        // 返回分页结果
        return PageResult.of(queryDTO.getPageNum(), queryDTO.getPageSize(), total, list);
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "更新分类状态")
    public boolean updateCategoryStatus(Integer id, Integer status) {
        return categoryMapper.updateStatusById(id, status) > 0;
    }
    
    @Override
    @BusinessLog(level = LogLevel.WARN, description = "批量删除分类")
    public boolean batchDeleteCategories(List<Integer> ids) {
        return categoryMapper.deleteBatchByIds(ids) > 0;
    }
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "根据代码获取分类")
    public Category getCategoryByCode(String code) {
        return categoryMapper.selectByCode(code);
    }

    // ==================== 统计功能实现 ====================
    
    @Override
    @BusinessLog(level = LogLevel.INFO, description = "获取分类统计数据")
    public Map<String, Object> getCategoryStats() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取分类统计数据
            List<Map<String, Object>> categoryStats = categoryMapper.selectCategoryStats();
            
            // 提取分类名称和新闻数量
            List<String> categoryNames = new ArrayList<>();
            List<Integer> newsCounts = new ArrayList<>();
            List<Map<String, Object>> barData = new ArrayList<>();
            
            for (Map<String, Object> item : categoryStats) {
                String categoryName = item.get("categoryName").toString();
                Integer newsCount = Integer.valueOf(item.get("newsCount").toString());
                
                categoryNames.add(categoryName);
                newsCounts.add(newsCount);
                
                // 构建柱状图数据
                Map<String, Object> barItem = new HashMap<>();
                barItem.put("name", categoryName);
                barItem.put("value", newsCount);
                barData.add(barItem);
            }
            
            result.put("categoryNames", categoryNames);
            result.put("newsCounts", newsCounts);
            result.put("barData", barData);
            result.put("total", newsCounts.stream().mapToInt(Integer::intValue).sum());
            
        } catch (Exception e) {
            result.put("error", "获取分类统计数据失败: " + e.getMessage());
        }
        
        return result;
    }
}